import axios from 'axios'
import store from '../store'

const WX_APP_ID = store.getters.getAppId

const userinstance = axios.create({
  // baseURL: '/wxwork/wxws',
  timeout: 60 * 1000,
  headers: {
    sine_url: getUrl(), //  动态获取当前url，截取到index.html之前
    WX_REQUEST_CHANNEL: 'AXIOS_HTTP_REQUEST', // 固定
    WX_APP_ID: WX_APP_ID // 由后台提供，每个项目不同
  }
})

userinstance.interceptors.response.use(
  res => {
    if (res.status === 200) {
      if (res.data.code === -1) {
        window.location.href = res.data.data
      }
      return Promise.resolve(res.data)
    }
    return Promise.reject(res)
  },
  error => {
    return Promise.reject(error)
  }
)

function getUrl () {
  const url = location.href
  const _index = url.indexOf('#')
  if (_index !== -1) {
    return url.substring(0, _index)
  }
  return url
}

export function getUser () {
  return userinstance({
    method: 'get',
    url: '/wxwork/auth/app/getCurrentUser'
  })
}